package algorithm;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author Panbo Guo
 * @date 2021/7/14
 */
public class TreeUtils {

    /**
     * 构造树
     * @param arr 数组
     * @return 树
     */
    public static TreeNode buildTree(Integer[] arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        TreeNode treeRoot = new TreeNode(arr[0]);
        if (arr.length == 1){
            return new TreeNode(arr[0]);
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(treeRoot);
        for (int i = 1; ;) {
            TreeNode root = queue.poll();
            if (root == null) {
                break;
            }
            // 构造左节点
            if (arr[i] != null) {
                TreeNode left = new TreeNode(arr[i]);
                root.left = left;
                queue.offer(left);
            }
            if (++ i >= arr.length) {
                break;
            }
            // 构造右节点
            if (arr[i] != null) {
                TreeNode right = new TreeNode(arr[i]);
                root.right = right;
                queue.offer(right);
            }
            if (++ i >= arr.length) {
                break;
            }
        }
        return treeRoot;
    }
}
